package com.example.cd5160866.tabs.camera;

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceView;
import android.widget.Toast;

import java.io.IOException;

/**
 * Created by cd5160866 on 2018/8/24.
 */

public class CameraView extends SurfaceView implements CameraAction {

    private Camera camera;

    public CameraView(Context context) {
        this(context, null);
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
    }

    @Override
    public void openCamera() {
        camera = Camera.open();
        if (null == camera) {
            Log.w("qw", "无摄像头");
        }
    }

    @Override
    public void startPreview() {
        if (null != camera) {
            //设置surfaceHolder
            try {
                camera.setPreviewDisplay(getHolder());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //开启预览
            camera.startPreview();
        }
    }

    @Override
    public void takePhoto() {
        camera.takePicture(null, null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                Toast.makeText(getContext(), "拍照完成", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void release() {
        if (null != camera) {
            camera.release();
        }
    }

}
